package com.qf.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String mark = req.getParameter("mark");
        //如果mark==null/"" 就没调用方法
        if (mark == null || "".equals(mark)) {
            throw new RuntimeException("没有执行任何的方法");
        }
        // 如果有mark 就通过反射调用方法
        //获取本类的 class对象 （可以获取子类的class类）
        try {
            Class cla = this.getClass();
            //获取Method对象
            Method m = cla.getMethod(mark, HttpServletRequest.class, HttpServletResponse.class);
            //调用方法
            m.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
